package types

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"net/http"
	"time"
)

type Result struct {
	Ctx *gin.Context
}

type Response struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	//Data      interface{} `json:"data,omitempty"`
}

func NewResult(ctx *gin.Context) *Result {
	return &Result{Ctx: ctx}
}

// Success 成功
func (r *Result) Success(data interface{}) {
	requestId, _ := r.Ctx.Get("RequestId")
	r.Ctx.Set("ReqStatus", "success")
	r.Ctx.JSON(http.StatusOK, gin.H{"result": data, "requestId": requestId.(string)})
}

// ErrorCode 出错,接受code和msg
func (r *Result) ErrorCode(code int, msg string) {
	if code == Success {
		r.Ctx.Set("ReqStatus", "success")
		r.Success(gin.H{})
		return
	}
	res := Response{}
	res.Code = code
	res.Message = msg
	if msg == "" {
		res.Message = Msg[code]
	}
	r.Ctx.Set("ReqStatus", "failed")
	requestId, _ := r.Ctx.Get("RequestId")
	r.Ctx.JSON(http.StatusOK, gin.H{
		"error": res, "requestId": requestId.(string)})
}

type SocketIoResult struct{}

func NewSocketIoResult() *SocketIoResult {
	return &SocketIoResult{}
}
func (s *SocketIoResult) Success(data interface{}, requestId string) map[string]interface{} {
	resp := map[string]interface{}{}
	if requestId != "" {
		resp["RequestId"] = requestId
	} else {
		resp["RequestId"] = fmt.Sprintf("watch-%s-%03d", time.Now(), rand.Int())
	}
	resp["result"] = data
	return resp
}

func (s *SocketIoResult) ErrorCode(code int, msg string, requestId string) map[string]interface{} {
	resp := map[string]interface{}{}
	res := Response{}
	res.Code = code
	res.Message = msg
	if msg == "" {
		res.Message = Msg[code]
	}
	resp["error"] = res
	if requestId != "" {
		resp["RequestId"] = requestId
	} else {
		resp["RequestId"] = fmt.Sprintf("watch-%s-%03d", time.Now(), rand.Int())
	}
	return resp
}
